package com.example.service;

import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


/***
 *
 * zk主从架构
 */
@Service
public class LeaderLatchService implements InitializingBean, DisposableBean {

    public static final String LEADERLATCH = "/zookeeper/leader";

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private ZookeeperService zookeeperService;

    private LeaderLatch leaderLatch;

    @Override
    public void afterPropertiesSet() throws Exception {
        this.leaderLatch = new LeaderLatch(zookeeperService.getCuratorFramework(), LEADERLATCH);
        this.leaderLatch.addListener(new LeaderLatchListener() {
            @Override
            public void isLeader() {
                logger.warn("===================>>>> isLeader isLeader isLeader ===================>>>>");
            }

            @Override
            public void notLeader() {
                logger.warn("notLeader notLeader notLeader ...");
            }
        });
        this.leaderLatch.start();
    }

    @Override
    public void destroy() throws Exception {
        this.leaderLatch.close();
    }
}
